﻿using Microsoft.Extensions.Logging;
using CNative.Cloud.CPlatform;
using CNative.Cloud.CPlatform.Module;
using CNative.Cloud.CPlatform.Utilities;
using System;
using System.Collections.Generic;
using System.Text;
using Autofac;
using Microsoft.Extensions.Configuration;
using Exceptionless.Extensions.Logging;
using ExceptionlessLogging = Exceptionless.Logging;

namespace CNative.Cloud.Exceptionless
{
    public class ExceptionlessModule : EnginePartModule
    {
        private bool isProvider = false;
        public override void Initialize(AppModuleContext context)
        {
            if (!isProvider)
            {
                var serviceProvider = context.ServiceProvoider;
                base.Initialize(context);

                if (AppConfig.ExceptionlessOption.UseExceptionless.ToLower() == "true" || AppConfig.ExceptionlessOption.UseExceptionless == "1")
                {
                    var provider = new ExceptionlessLoggerProvider((cf) =>
                       {
                           try
                           {
                               cf.ApiKey = AppConfig.ExceptionlessOption.ApiKey;
                               cf.ServerUrl = AppConfig.ExceptionlessOption.ServerUrl;

                               var logLevel = AppConfig.ExceptionlessOption.LogLevel;
                               cf.SetDefaultMinLogLevel(ExceptionlessLogging.LogLevel.FromString(logLevel));
                           }
                           catch { }
                       });
                    serviceProvider.Resolve<ILoggerFactory>().AddProvider(provider);
                }
                isProvider = true;
            }

        }

        /// <summary>
        /// Inject dependent third-party components
        /// </summary>
        /// <param name="builder"></param>
        protected override void RegisterBuilder(ContainerBuilderWrapper builder)
        {
            var section = CPlatform.AppConfig.GetSection("Exceptionless");
            if (section.Exists())
            {
                AppConfig.ExceptionlessOption = section.Get<ExceptionlessOption>();
            }

        }
    }
}
